package com.wechat.scheme.handler;

import cn.hutool.core.util.RandomUtil;
import com.wechat.scheme.builder.ImageBuilder;
import com.wechat.scheme.builder.TextBuilder;
import com.wechat.scheme.utils.WxFileUtils;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpMaterialService;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpMaterialServiceImpl;
import me.chanjar.weixin.mp.bean.material.WxMpMaterialFileBatchGetResult;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.stereotype.Component;

import java.io.File;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;

import static me.chanjar.weixin.common.api.WxConsts.XmlMsgType;


@Slf4j
@Component
public class MsgImageHandler extends AbstractHandler {


    private static final String temple_str = "抱歉,-_-暂时不支持图片智能OCR识别,功能开发ing";


    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context, WxMpService weixinService,
                                    WxSessionManager sessionManager) {

        if (!wxMessage.getMsgType().equals(XmlMsgType.EVENT)) {
            //TODO 可以选择将消息保存到本地
        }
        try {
            //尝试处理image
            WxMpMaterialService wxMpMaterialService = new WxMpMaterialServiceImpl(weixinService);
//            WxMpMaterial wxMpMaterial = new WxMpMaterial();
//            String imageName = UUID.randomUUID().toString().replace("-", "") + ".jpg";
//            wxMpMaterial.setName(imageName);
//             file = this.getFile(wxMessage.getPicUrl(), imageName);
//            wxMpMaterial.setFile(file);
//            wxMpMaterialService.materialFileUpload(WxConsts.MediaFileType.IMAGE, wxMpMaterial);
            WxMpMaterialFileBatchGetResult result = wxMpMaterialService.materialFileBatchGet("image", 0, 20);
            if(result.getTotalCount()>0){
                int randomIndex = RandomUtil.randomInt(result.getItemCount() - 1);
                log.info("image msg temple size: {},randomIndex:{}",result.getTotalCount(),randomIndex);
                String mediaId = result.getItems().get(randomIndex).getMediaId();
                return new ImageBuilder().build(mediaId, wxMessage, weixinService);
            }
            return new TextBuilder().build(temple_str, wxMessage, weixinService);
        } catch (WxErrorException e) {
            e.printStackTrace();
            return new TextBuilder().build(temple_str, wxMessage, weixinService);
        }finally {
        }


    }

    /**
     * 测试
     */
    public File getFile(String path, String name) {
        File file = null;
        try {
            HttpURLConnection httpUrl = (HttpURLConnection) new URL(path).openConnection();
            httpUrl.connect();
            file = WxFileUtils.inputStreamToFile(httpUrl.getInputStream(), name);
            System.out.println("转存file====>>>>" + file.getPath());
            httpUrl.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }


}
